import random
import sys
import subprocess


_FuckSoftReset = 'FuckSoftReset'
_m4aSoundVSyncOff = 'm4aSoundVSyncOff'
_ScanlineEffect_Stop = 'ScanlineEffect_Stop'
_SiiRtcProtect = 'SiiRtcProtect'


def dump_object(link_file):
    out = subprocess.check_output(['arm-none-eabi-objdump', '-t', link_file])
    lines = out.decode().split('\n')

    ret = {}

    for line in lines:
        data = line.split()
        if len(data) == 6:
            ret[data[5]] = int(data[0], 16)
        elif len(data) == 5: #汇编
            ret[data[4]] = int(data[0], 16)
    return ret


def encr_softreset(in_file, arg: str):
    symbols = dump_object(arg)

    with open(in_file, 'rb+') as file:
        start = symbols[_FuckSoftReset] - 0x8000000
        print("_FuckSoftReset: ", hex(start))
        func1 = (symbols[_m4aSoundVSyncOff])
        print("m4aSoundVSyncOff: ", hex(func1 - 0x8000000))
        func2 = (symbols[_ScanlineEffect_Stop])
        print("ScanlineEffect_Stop: ", hex(func2 - 0x8000000))
        func3 = (symbols[_SiiRtcProtect])
        print("SiiRtcProtect: ", hex(func3 - 0x8000000))
        file.seek(start + 192)
        file.write((func1 | 1).to_bytes(4, 'little'))
        file.write((func2 | 1).to_bytes(4, 'little'))
        file.write((func3 | 1).to_bytes(4, 'little'))
        file.seek(start)
        i = 0
        while i < 51:
            raw = int.from_bytes(file.read(4), 'little')
            print(hex(raw))
            raw ^= 0xFFFFFFFF
            file.seek(-4, 1)
            file.write(raw.to_bytes(4, 'little'))
            i += 1


encr_softreset(sys.argv[1], sys.argv[2])